package zpy.servlet.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import zpy.servlet.pojo.Student;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;



/**
 * Servlet Filter implementation class loginFilter
 */
@WebFilter(
		dispatcherTypes = {DispatcherType.REQUEST },
		description = "登录拦截器",
		urlPatterns = { "/*" },
		initParams = {
				@WebInitParam(name = "noFilterUrls", value = "/login.jsp;/login;/image;/js;/css", description = "不拦截url")
		})
public class loginFilter implements Filter, goLogin {
	private List<String> noFilterUrlsList = new ArrayList<String>();
	/**
	 * Default constructor.
	 */
	public loginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		String noFilterUrls = fConfig.getInitParameter("noFilterUrls");
		if (noFilterUrls != null) {
			String[] urls = noFilterUrls.split(";");
			for(String url:urls){
				noFilterUrlsList.add(url);
			}
		}
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest hRequest = (HttpServletRequest) request;
		String servletPath = hRequest.getServletPath();
		String pathInfo    = hRequest.getPathInfo();
		String url = servletPath + (pathInfo == null?"":pathInfo);

		String path = hRequest.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

		if (checkUrl(url)) {
			HttpSession session = hRequest.getSession(false);
			if (session == null) {
				//转到登录界面
				//hRequest.getRequestDispatcher("/login.jsp").forward(hRequest, response);
				goLgin(response, basePath);
				return;
			}else{
				Student student = (Student) session.getAttribute("student");
				if (student == null) {
					goLgin(response, basePath);
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}

	private boolean checkUrl(String url) {
		if (!noFilterUrlsList.contains(url)) {
			return false;
		}else{
			for (String noFilterUrl : noFilterUrlsList) {
				if (url.contains(noFilterUrl)) {
					return false;
				}
			}
		}
		return true;
	}
	private void goLgin(ServletResponse response, String basePath) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		Writer writer = response.getWriter();
		writer.write("<script>window.open('"+basePath + "login.jsp','_top')</script>");
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

}
